package com.woniu.service.impl;

import com.woniu.entity.Reg;
import com.woniu.entity.User1;
import com.woniu.mapper.*;
import com.woniu.pojo.*;
import com.woniu.service.UserService;
import com.woniu.utils.PasswordMd5;
import com.woniu.utils.PinYin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.UnsatisfiedServletRequestParameterException;

import javax.swing.filechooser.FileSystemView;
import java.io.*;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional

public class UserServiceImpl implements UserService {

    @Autowired
    UserDao userDao;
    @Autowired
    StudentDao studentDao;
    @Autowired
    CompanyDao companyDao;
    @Autowired
    EmpDao empDao;
    @Autowired
    RolepowerDao rolepowerDao;
    @Autowired
    PowerDao powerDao;
    @Autowired
    EmproleDao emproleDao;
    @Autowired
    RoleDao roleDao;

    @Override
    public void add(User user) {
        userDao.insert(user);
    }

    @Override
    public void deleteById(Integer userId) {
        userDao.deleteByPrimaryKey(userId);
    }

    @Override
    public void deleteByExample(Integer[] userId) {
        UserExample userExample=new UserExample();
        userExample.createCriteria().andUserIdIn(Arrays.asList(userId));
        userDao.deleteByExample(userExample);
    }

    @Override
    public void updateByExample(User user) {
        if(user.getUserPwd()!=null){
            try {
            user.setUserPwd(PasswordMd5.getMD5String(user.getUserPwd()));
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }
        userDao.updateByPrimaryKeySelective(user);
    }

    @Override
    public List<User> findAll(User user) {
        UserExample userExample=new UserExample();
        userExample.setOrderByClause("user_id desc");
        UserExample.Criteria criteria = userExample.createCriteria();
        if (user.getUserName()!=null&&!user.getUserName().equals("")) {
            criteria.andUserNameLike("%"+user.getUserName()+"%");
        }
        if (user.getUserStatus()!=null&&!user.getUserStatus().equals("")) {
            criteria.andUserStatusEqualTo(user.getUserStatus());
        }
        List<User> users = userDao.selectByExample(userExample);
        return users;
    }

    @Override
    public void findOne(Integer userId) {
        userDao.selectByPrimaryKey(userId);
    }

  @Override
    public  Map<String,Object> login(User user, String roleStatus) {
        Map<String,Object> map=new HashMap<>();
        List<Power> tree=new ArrayList<>();
        Map<Integer,Power> map1=new HashMap<>();
        User1 users=new User1();
        UserExample userExample = new UserExample();
        String pwd=null;
        try {
             pwd= PasswordMd5.getMD5String(user.getUserPwd());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        userExample.createCriteria().andUserNameEqualTo(user.getUserName()).andUserPwdEqualTo(pwd);
        List<User> user1 = userDao.selectByExample(userExample);

        if (user1 != null && user1.size() > 0) {
           users.setUser(user1.get(0));
           users.setRoleStatus(roleStatus);
            switch (roleStatus) {
                //学生
                case "2":
                    StudentExample studentExample = new StudentExample();
                    studentExample.createCriteria().andUserIdEqualTo(users.getUser().getUserId());
                    List<Student> students = studentDao.selectByExample(studentExample);
                    users.setUid(students.get(0).getStudentId());
                    users.setUname(students.get(0).getStudentName());
                    if(students.get(0).getRoleId()!=null){
                        RolepowerExample example=new RolepowerExample();
                        example.createCriteria().andRoleIdEqualTo(students.get(0).getRoleId());
                        List<Rolepower> rolepowers = rolepowerDao.selectByExample(example);
                        List<Integer> p=new ArrayList<>();
                        for(Rolepower e:rolepowers){
                            p.add(e.getPowerId());
                        }
                        PowerExample powerExample=new PowerExample();
                        powerExample.createCriteria().andPowerIdIn(p);
                        List<Power> powers = powerDao.selectByExample(powerExample);
                        for(Power e:powers){
                            map1.put(e.getPowerId(),e);
                        }
                        for(Power e:powers){
                            if(e.getParentId()==null){
                                tree.add(e);
                            }else{
                                map1.get(e.getParentId()).getChildren().add(e);
                            }
                        }

                    }


                    break;

                //公司
                case "3":
                    CompanyExample companyExample = new CompanyExample();
                    companyExample.createCriteria().andUserIdEqualTo(users.getUser().getUserId());
                    List<Company> companies = companyDao.selectByExample(companyExample);
                    users.setUid(companies.get(0).getCompanyId());
                    users.setUname(companies.get(0).getCompanyName());
                    if(companies.get(0).getRoleId()!=null){
                        RolepowerExample example=new RolepowerExample();
                        example.createCriteria().andRoleIdEqualTo(companies.get(0).getRoleId());
                        List<Rolepower> rolepowers = rolepowerDao.selectByExample(example);
                        List<Integer> p=new ArrayList<>();
                        for(Rolepower e:rolepowers){
                            p.add(e.getPowerId());
                        }
                        PowerExample powerExample=new PowerExample();
                        powerExample.createCriteria().andPowerIdIn(p);
                        List<Power> powers = powerDao.selectByExample(powerExample);
                        for(Power e:powers){
                            map1.put(e.getPowerId(),e);
                        }
                        for(Power e:powers){
                            if(e.getParentId()==null){
                                tree.add(e);
                            }else{
                                map1.get(e.getParentId()).getChildren().add(e);
                            }
                        }

                    }
                  break;
                //员工
                case "1":
                    EmpExample empExample = new EmpExample();
                    empExample.createCriteria().andUserIdEqualTo(users.getUser().getUserId());
                    List<Emp> emps = empDao.selectByExample(empExample);
                    users.setUid(emps.get(0).getEmpId());
                    users.setUname(emps.get(0).getEmpName());

                    if(emps.get(0).getEmpId()!=null){
                        EmproleExample emproleExample=new EmproleExample();
                        emproleExample.createCriteria().andEmpIdEqualTo(emps.get(0).getEmpId());
                        List<Emprole> emproles = emproleDao.selectByExample(emproleExample);

                        List<Integer> p=new ArrayList<>();
                        if(emproles!=null&&emproles.size()>0){
                            for(Emprole e:emproles){
                                p.add(e.getRoleId());
                            }
                            RolepowerExample rolepowerExample=new RolepowerExample();
                            rolepowerExample.createCriteria().andRoleIdIn(p);
                            List<Rolepower> rolepowers = rolepowerDao.selectByExample(rolepowerExample);
                            List<Integer> p1=new ArrayList<>();
                            if(rolepowers!=null&&rolepowers.size()>0){
                                for(Rolepower e:rolepowers) {
                                    p1.add(e.getPowerId());
                                }
                                PowerExample powerExample=new PowerExample();
                                powerExample.createCriteria().andPowerIdIn(p1);
                                List<Power> powers = powerDao.selectByExample(powerExample);
                                    if(powers!=null&&powers.size()>0){
                                        for(Power e:powers){
                                            map1.put(e.getPowerId(),e);
                                        }
                                        for(Power e:powers){
                                            if(e.getParentId()==null){
                                                tree.add(e);
                                            }else{
                                                map1.get(e.getParentId()).getChildren().add(e);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                   break;
                default:
                    break;


                }

            }
        map.put("user",users);
        map.put("tree",tree);
        return map;

        }

    @Override
    public Map<String, Object> findUserInfo(User1 user) {
        Map<String, Object> map = new HashMap<>();
        switch (user.getRoleStatus()) {
            //学生
            case "2":
                Student student = studentDao.selectByPrimaryKey(user.getUid());
                map.put("user", student);
                break;

            //公司
            case "3":
                Company company = companyDao.selectByPrimaryKey(user.getUid());
                map.put("user", company);
                break;
            //员工
            case "1":
                Emp emp = empDao.selectByPrimaryKey(user.getUid());
                map.put("user", emp);
                break;
            default:
                break;
        }
        return map;
    }

    /**
     * 重置密码
     * @param userId
     */
    @Override
    public void resetPwd(Integer userId) {
        User user=new User();
        user.setUserId(userId);
        try {
            user.setUserPwd(PasswordMd5.getMD5String("123456"));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        userDao.updateByPrimaryKeySelective(user);
    }

    @Override
    public void addCompany(Reg reg ,Integer uid) {
        User user = getUserId(reg);
        Company company=new Company();
        company.setCompanyName(reg.getName());
        company.setCompanyPhone(reg.getPhone());
        company.setEmpId(uid);
        company.setUserId(user.getUserId());
        //        得到公司角色的id，并存入公司角色
        RoleExample roleExample=new RoleExample();
        roleExample.createCriteria().andRoleNameEqualTo("学生");
        List<Role> list = roleDao.selectByExample(roleExample);
        int roleId=list.get(0).getRoleId();
        company.setRoleId(roleId);
        companyDao.insertSelective(company);
        //        添加成功将其信息存入文件
        reg.setUserName(user.getUserName());
        saveNewUser(reg);
    }

    @Override
    public int addEmp(Reg reg) {
        Emp emp=new Emp();
        User user = getUserId(reg);
        emp.setUserId(user.getUserId());
        emp.setEmpName(reg.getName());
        emp.setDeptId(reg.getDeptId());
        emp.setEmpHiredate(new Date());
        emp.setEmpPhone(reg.getPhone());
        int i = empDao.insertSelective(emp);

        reg.setUserName(user.getUserName());
        saveNewUser(reg);
        return i;
    }

    @Override
    public void addStudent(Reg reg) {
        Student student=new Student();
        User user = getUserId(reg);
        student.setStudentIntotime(new Date());
        student.setStudentName(reg.getName());
        student.setStudentNumber(getStudentNum());
        student.setStudentPhone(reg.getPhone());
        student.setStudentStatus("在校");
        student.setClassId(reg.getClassId());
        student.setUserId(user.getUserId());
//        得到学生角色的id，并存入学生角色
        RoleExample roleExample=new RoleExample();
        roleExample.createCriteria().andRoleNameEqualTo("学生");
        List<Role> list = roleDao.selectByExample(roleExample);
        int roleId=list.get(0).getRoleId();
        student.setRoleId(roleId);
        studentDao.insertSelective(student);

//        添加成功将其信息存入文件
       reg.setUserName(user.getUserName());
       saveNewUser(reg);

    }

    public void saveNewUser(Reg reg) {
        //获得当前时间
        Date d=new Date();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String date=sdf.format(d);
        //        获得存入文件的信息
        String str=date+"  名称:"+reg.getName()+"  账号:"+reg.getUserName()+"  默认密码:123456"+"  电话:"+reg.getPhone();
        File desktopDir = FileSystemView.getFileSystemView() .getHomeDirectory();
        File f=null;
        if (reg.getUserStatus().equals("1")) {
            f=new File(desktopDir,"emp.txt");
        }else if (reg.getUserStatus().equals("2")) {
            f=new File(desktopDir,"student.txt");
        }else{
            f=new File(desktopDir,"company.txt");
        }
        //判断文件是否存在并创建
        if (!f.exists()) {
            try {
                f.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            Writer wri=new FileWriter(f,true);
            BufferedWriter writer=new BufferedWriter(wri);
            writer.write(str);
            writer.newLine();
            writer.flush();
            writer.close();
            wri.flush();
            wri.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取新学生的学号
     */
    @Override
    public Integer getStudentNum(){
        Integer newStuNum=null;
        StudentExample studentExample=new StudentExample();
        studentExample.setOrderByClause("student_id desc");
        studentExample.setLimit(1);
        //得到数据数学号最大的学生学号
        List<Student> students = studentDao.selectByExample(studentExample);
        Student student=students.get(0);
        System.out.println(student);
        Integer maxNum = student.getStudentNumber();
        //得到老的学号前4位年份
        String oldYear=null;
        if (maxNum!=null) {
            String strMaxNum = maxNum.toString();
            oldYear = strMaxNum.substring(0,4);
        }

        //得到现在的年份
        Date date=new Date();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(date);
        String newYear = format.substring(0,4);
        //如果现在的年份和上一个学生的年份相同则给上一个学生的学号➕1
        //如果不同则用现在的年份➕10001作为学号
        if (oldYear!=null) {
            if (oldYear.equals(newYear)) {
                newStuNum=maxNum+1;
            }else {
                newStuNum=Integer.parseInt(newYear)+10001;
            }
        }else{
            newStuNum=Integer.parseInt(newYear+10001);
        }

        return newStuNum;
    }

    /**
     * 判断userName是否可用
     * @param userName
     * @return
     */
    @Override
    public String judgeUserName(String userName) {
        UserExample userExample=new UserExample();
        userExample.createCriteria().andUserNameEqualTo(userName);
        List<User> users = userDao.selectByExample(userExample);
        if (users.size()==0) {
            return "ok";
        }
        return null;
    }

    /**
     * 获得新添加的userId
     * @param user
     * @return
     */
    @Override
    public User getUserId(Reg user){
        String pinName=null;
        User u=new User();
        if (user.getUserStatus().equals("3")) {
            pinName=PinYin.ToFirstChar(user.getName()).toUpperCase();
        }else{
            pinName=PinYin.ToPinyin(user.getName());
            pinName+=(int) (Math.random() * 9000 + 1000);
        }
        u.setUserName(pinName);
        String pwd=null;
        try {
            pwd=PasswordMd5.getMD5String("123456");
            u.setUserPwd(pwd);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        u.setUserStatus(user.getUserStatus());
        userDao.insert(u);

        UserExample userExample=new UserExample();
        userExample.createCriteria().andUserNameEqualTo(pinName).andUserPwdEqualTo(pwd)
                .andUserStatusEqualTo(user.getUserStatus());
        List<User> users = userDao.selectByExample(userExample);
        return users.get(0);
    }
}

